package edu.iiitb.studentinfo.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import edu.iiitb.studentinfo.model.*;
import edu.iiitb.studentinfo.service.LoginService;
import edu.iiitb.studentinfo.service.StudentService;

public class LoginAction extends ActionSupport {
	
	private static final long serialVersionUID = 5311892150298424579L;
	private int studentId;
	private String username;
	private String password;
	
	
	private ArrayList<Announcement> announcements;
	
	private Map session;
	
	// action methods
	public String execute() {
		
		LoginService loginService = new LoginService();
		
		this.studentId = loginService.authenticate(username, password);
		
		if(this.studentId > 0) {
			session=ActionContext.getContext().getSession();
			session.put("userid", this.studentId);
			return "success";
		}
		else if(studentId == 0) {
			addFieldError("username", "username and password incorrect");
			return "failure";
		}
		else {
			addFieldError("username", "database connectivity error");
			return "error";
		}
		
		
	}
	
	
	public String show() {
		LoginService loginService = new LoginService();
		announcements = new ArrayList<Announcement>();
		setAnnouncements(loginService.getAllAnnouncements());
		
		
//		for(Announcement an : announcements) {
//			System.out.println(an.getAnnouncement());
//		}
		
		return "success";
	}

	
	// getters and setters
	
	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		return username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	

	public void setAnnouncements(ArrayList<Announcement> announcements) {
		this.announcements = announcements;
	}


	public ArrayList<Announcement> getAnnouncements() {
		return announcements;
	}
	public int getStudentId() {
		return studentId;
	}


	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
}

